package com.lykj.modules.shop.mapper;

import com.lykj.modules.shop.entity.UserBonus;
import com.lykj.modules.shop.excel.UserBonusExcel;
import com.lykj.modules.shop.vo.UserBonusVO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.util.List;

/**
 * 红包表 Mapper 接口
 *
 * @author cxl
 * @since 2022-01-14
 */
public interface UserBonusMapper extends BaseMapper<UserBonus> {

	/**
	 * 自定义分页
	 *
	 * @param page
	 * @param userBonus
	 * @return
	 */
	List<UserBonusVO> selectUserBonusPage(IPage page, UserBonusVO userBonus);

	/**
	 * 更改红包状态
	 * @param id
	 */
	@Update("update `shsy_user_bonus` set status = 1,receive_time=NOW() where id = #{id}")
	void bonusStatus(@Param("id") Long id);
	/**
	 * 删除红包
	 * @param id
	 */
	@Update("update `shsy_user_bonus` set is_deleted = 1 where id = #{id}")
	void bonusDeleted(@Param("id") Long id);

	/**
	 * 获取累计分红总额
	 * @param userId
	 */
	@Select("select if(sum(b.number) is null,0,sum(b.number)) from shsy_user_bonus b where b.user_id=#{userId} and b.`status`=1 and b.is_deleted=0")
	BigDecimal bonusTotal(@Param("userId") Long userId);

	/**
	 * 获取累计分红总额
	 * @param orderId
	 */
	@Select("select if(sum(b.number) is null,0,sum(b.number)) from shsy_user_bonus b where b.order_id=#{orderId} and b.`status`=1 and b.is_deleted=0")
	BigDecimal bonusTotalByOrder(@Param("orderId") Long orderId);

	/**
	 * 获取累计分红总额
	 */
	@Select("select if(sum(b.number) is null,0,sum(b.number)) from shsy_user_bonus b where b.`status`=1 and b.is_deleted=0")
	BigDecimal sumBonus();

	@Select("<script>select b.*,u.account, u.uid from shsy_user_bonus b LEFT JOIN lykj_user u ON u.id=b.user_id where b.is_deleted = 0" +
		"<if test=\"userBonus.id!=null and userBonus.id!=''\">" +
		" and b.id = #{userBonus.id}" +
		"</if>" +
		"<if test=\"userBonus.tenantId!=null and userBonus.tenantId!=''\">" +
		" and b.tenant_id = #{userBonus.tenantId}" +
		"</if>" +
		"<if test=\"userBonus.userId!=null and userBonus.userId!=''\">" +
		" and b.user_id = #{userBonus.userId}" +
		"</if>" +
		"<if test=\"userBonus.account!=null and userBonus.account!=''\">" +
		" and u.account = #{userBonus.account}" +
		"</if>" +
		"<if test=\"userBonus.uid!=null and userBonus.uid!=''\">" +
		" and u.uid = #{userBonus.uid}" +
		"</if>" +
		"<if test=\"userBonus.status!=null\">" +
		" and b.status = #{userBonus.status}" +
		"</if>" +
		"<if test=\"userBonus.startDate!=null and userBonus.endDate!=null\">" +
		" and b.create_time BETWEEN CONCAT(#{userBonus.startDate},' 00:00:00') AND CONCAT(#{userBonus.endDate},' 23:59:59')" +
		"</if>" +
		"</script>")
	List<UserBonusExcel> export(@Param("userBonus") UserBonusVO userBonus);
}
